<template>
  <el-card shadow="never">
    <el-form :model="searchForm" label-width="auto" size="small" :inline="true">
      <el-row>
        <el-col :span="6">
          <el-form-item label="合同编号" style="width: 85%">
            <el-input
              v-model="searchForm.contractNo"
              placeholder="请输入 合同编号"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="合同名称" style="width: 85%">
            <el-select
              v-model="searchForm.contractName"
              clearable
              filterable
              remote
              remote-show-suffix
              placeholder="请选择 合同名称"
              :remote-method="getContractNameList"
              size="small"
            >
              <el-option
                v-for="item in contractOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="项目名称" style="width: 85%">
            <el-select
              v-model="searchForm.projectName"
              clearable
              filterable
              remote
              remote-show-suffix
              placeholder="请选择 合同名称"
              :remote-method="getProjectNameList"
              size="small"
            >
              <el-option
                v-for="item in projectOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="所属公司" style="width: 85%">
            <el-input
              v-model="searchForm.projectDeptName"
              clearable
              placeholder="请输入 所属公司"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="6">
          <el-form-item label="供应商名称" style="width: 85%">
            <el-input
              v-model="searchForm.supplierDeptName"
              placeholder="请输入 供应商名称"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="日期" style="width: 85%">
            <el-date-picker
              v-model="searchForm.signDate"
              type="daterange"
              range-separator="-"
              start-placeholder="开始"
              end-placeholder="结束"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24" style="text-align: right">
          <el-button
            color="#1E3485"
            size="small"
            icon="Download"
            @click="getList(true)"
          >导出</el-button
          >
          <el-button
            color="#1E3485"
            size="small"
            :icon="Edit"
            @click="
              toDetail(
                { title: '新建采购合同', action: 'add', contractType: '0' },
                'addContract'
              )
            "
            >新建</el-button
          >
          <el-button
            color="#1E3485"
            size="small"
            :icon="Search"
            @click="
              tablePage.currentPage = 1;
              getList();
            "
            >搜索</el-button
          >
          <el-button
            type="default"
            size="small"
            :icon="Delete"
            @click="clearAllFields"
            >清空</el-button
          >
        </el-col>
      </el-row>
    </el-form>
    <vxe-table
      border
      min-height="300"
      header-align="center"
      :column-config="{ resizable: true }"
      :row-config="{ isHover: true }"
      :data="salesContractTableData"
      size="mini"
      :loading="tableLoading"
      :pager-config="tablePage"
      style="margin-top: 1%"
    >
      <vxe-column
        v-for="column in salesContractTableColumns"
        :key="column.field"
        header-align="center"
        :field="column.field"
        :title="column.title"
        :fixed="column.fixed"
        :min-width="column.width"
        :align="column.align"
        show-overflow
      >
        <template v-slot:default="{ row }">
          <span
            v-if="column.field === 'auditStatus'"
            :style="{ color: getStatusColor(row[column.field]) }"
          >
            {{ auditStatusMap[row[column.field]] }}
          </span>
          <span v-else>
            {{ row[column.field] }}
          </span>
        </template>
      </vxe-column>
      <vxe-column title="操作" min-width="250" align="center" fixed="right">
        <template v-slot:default="{ row }">
          <vxe-button
            v-if="
              row.auditStatus === '0' ||
              row.auditStatus === '3' ||
              row.auditStatus === '4'
            "
            type="text"
            size="small"
            @click="
              toDetail(
                { id: row.id, title: row.contractName, action: 'edit' },
                'editContractDetail'
              )
            "
          >
            编辑
          </vxe-button>
          <vxe-button
            type="text"
            size="small"
            @click="
              toDetail({ id: row.id, title: row.contractName }, 'viewContract')
            "
          >
            查看
          </vxe-button>
          <vxe-button
            v-if="
              row.auditStatus === '0' ||
              row.auditStatus === '3' ||
              row.auditStatus === '4'
            "
            type="text"
            size="small"
            @click="rowDelete(row.id)"
          >
            删除
          </vxe-button>
          <vxe-button
            v-if="
              row.auditStatus === '0' ||
              row.auditStatus === '3' ||
              row.auditStatus === '4'
            "
            type="text"
            size="small"
            @click="rowExamine(row.id)"
          >
            提交审批
          </vxe-button>
          <vxe-button
            v-if="row.auditStatus === '1'"
            type="text"
            size="small"
            @click="rowWithdraw(row.id)"
          >
            撤回
          </vxe-button>
          <vxe-button
            v-if="row.auditStatus === '2'"
            type="text"
            size="small"
            @click="
              toDetail(
                {
                  id: row.id,
                  title: row.contractName,
                  action: 'edit',
                  examine: 'already'
                },
                'editContract'
              )
            "
          >
            过审编辑
          </vxe-button>
        </template>
      </vxe-column>
    </vxe-table>
    <vxe-pager
      v-model:current-page="tablePage.currentPage"
      v-model:page-size="tablePage.pageSize"
      :layouts="[
        'Sizes',
        'PrevJump',
        'PrevPage',
        'Number',
        'NextPage',
        'NextJump',
        'FullJump',
        'Total'
      ]"
      :total="tablePage.total"
      size="mini"
      style="margin-top: 2%"
      @page-change="handlePageChange"
    />
  </el-card>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUpdated } from "vue";
import { Delete, Search, Edit } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { VxePagerEvents } from "vxe-table";
import { useDetail } from "./hooks";
import {
  getProcureContractsList,
  delProcureContract,
  submitProcureContract,
  withdrawProcureContract
} from "@/api/ERP_procure";
import { getProjectList } from "@/api/ERP_public";
import { getDict } from "@/api/utils";
import {http} from "@/utils/http";
import {baseUrlApi} from "@/store/utils";

// 路由跳转
const { toDetail, router } = useDetail();
// 表单字段
let searchForm = reactive({
  contractType: "0", // 合同类型:0-主合同，1-补充合同
  contractNo: "", // 合同编号
  contractName: "", // 合同名称
  projectName: "", // 项目名称
  projectDeptName: "", // 所属公司
  supplierDeptName: "", // 供应商名称
  signDate: "" // 日期
});
// 合同名称选择
let contractOptions = ref([]);
// 项目名称选择
let projectOptions = ref([]);
// 合同状态选择
let auditStatusOptions = ref([]);
// 表格字段翻译
let auditStatusMap = {};
// 状态字段颜色
const getStatusColor = status => {
  switch (status) {
    case "0":
      return "blue";
    case "1":
      return "orange";
    case "2":
      return "green";
    case "3":
      return "red";
    case "4":
      return "gray";
    default:
      return "black";
  }
};
// 获取字典值
async function getAuditStatus() {
  let params: ApiParams = {};
  params.key = "contract_type";
  try {
    const response: ApiResponse = await getDict(params);
    auditStatusOptions.value = Object.keys(response.data).map(key => {
      return {
        label: response.data[key],
        value: key
      };
    });
    auditStatusMap = response.data;
  } catch (error) {
    ElMessage.error("获取合同状态列表失败");
  }
}
// 加载状态
let tableLoading = ref(false);
// 表格数据
let salesContractTableData = ref([]);
// 表格列
const salesContractTableColumns = ref([
  {
    field: "contractNo",
    title: "合同编号",
    fixed: "left",
    width: 200,
    align: "left"
  },
  {
    field: "contractName",
    title: "采购合同名称",
    fixed: "left",
    width: 200,
    align: "left"
  },
  {
    field: "projectName",
    title: "项目名称",
    width: 200,
    align: "left"
  },
  {
    field: "contractTotalPrice",
    title: "合同总额（元）",
    width: 150,
    align: "right"
  },
  {
    field: "signDate",
    title: "签订日期",
    width: 150,
    align: "center"
  },
  {
    field: "priceTypeDesc",
    title: "合同类型",
    width: 100,
    align: "center"
  },
  {
    field: "auditStatus",
    title: "状态",
    width: 100,
    align: "center"
  },
  {
    field: "projectDeptName",
    title: "所属公司",
    width: 200,
    align: "left"
  },
  {
    field: "supplierDeptName",
    title: "生产厂家（供应商）",
    width: 200,
    align: "left"
  }
]);
// 表格分页配置
let tablePage = reactive({
  total: 0,
  currentPage: 1,
  pageSize: 15
});
// 表格分页事件
const handlePageChange: VxePagerEvents.PageChange = ({
  currentPage,
  pageSize
}) => {
  tablePage.currentPage = currentPage;
  tablePage.pageSize = pageSize;
  getList();
};
// 合同名称列表下拉框
const getContractNameList = (query: string) => {
  getProcureContractsList({
    pageIndex: 1,
    pageSize: 10,
    contractType: "0",
    contractName: query
  }).then(response => {
    contractOptions.value = (response as any).data.records.map(item => ({
      label: item.contractName,
      value: item.contractName
    }));
  });
  if (query) {
    setTimeout(() => {
      getProcureContractsList;
    }, 1500);
  }
};
// 项目名称列表下拉框
const getProjectNameList = (query: string) => {
  getProjectList({
    pageIndex: 1,
    pageSize: 10,
    projectName: query
  }).then(response => {
    projectOptions.value = (response as any).data.records.map(item => ({
      label: item.projectName,
      value: item.projectName
    }));
  });
  if (query) {
    setTimeout(() => {
      getProjectList;
    }, 1500);
  }
};
// 获取表格数据
async function getList(isExport) {
  // 拼查询条件
  let params: ApiParams = {};

  if (searchForm.contractType) params.contractType = searchForm.contractType;
  if (searchForm.contractNo) params.contractNo = searchForm.contractNo;
  if (searchForm.contractName) params.contractName = searchForm.contractName;
  if (searchForm.projectName) params.projectName = searchForm.projectName;
  if (searchForm.projectDeptName)
    params.projectDeptName = searchForm.projectDeptName;
  if (searchForm.supplierDeptName)
    params.supplierDeptName = searchForm.supplierDeptName;
  if (searchForm.signDate) {
    params.beginDate = searchForm.signDate[0];
    params.endDate = searchForm.signDate[1];
  }
  if(isExport) {
    await http.request('get',baseUrlApi("purchase/export/file"), {params})
    return
  }
  params.pageIndex = tablePage.currentPage;
  params.pageSize = tablePage.pageSize;
  tableLoading.value = true;
  // 查询
  try {
    const response: ApiResponse = await getProcureContractsList(params);
    // 表格数据
    salesContractTableData.value = response.data.records;
    tablePage.total = response.data.totalElements;
  } catch (error) {
    ElMessage.error("获取表格数据失败");
  } finally {
    tableLoading.value = false;
  }
}
// 清空按钮点击事件
const clearAllFields = () => {
  for (const key in searchForm) {
    if (searchForm.hasOwnProperty(key)) {
      if (key === "signDate") {
        searchForm[key] = null;
      } else {
        searchForm[key] = "";
      }
    }
  }
  searchForm.contractType = "0";
};
// 删除按钮
const rowDelete = id => {
  ElMessageBox.confirm("确认删除选中的合同吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      let params: ApiParams = {};
      params.id = id;
      delProcureContract(params).then((response: ApiResponse) => {
        if (response.code === 200) {
          ElMessage.success("删除成功");
        } else {
          ElMessage.error("删除失败");
          ElMessage.error("失败原因：" + response.msg);
        }
        getList();
      });
    })
    .catch(() => {
      ElMessage.error("已取消");
    });
};
// 提交审批按钮
const rowExamine = id => {
  ElMessageBox.confirm("确认提交该合同审批吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      let params: ApiParams = {};
      params.id = id;
      submitProcureContract(params).then((response: ApiResponse) => {
        if (response.code === 200) {
          ElMessage.success("提交成功");
        } else {
          ElMessage.error("提交失败");
          ElMessage.error("失败原因：" + response.msg);
        }
        getList();
      });
    })
    .catch(() => {
      ElMessage.error("已取消");
    });
};
// 撤回按钮
const rowWithdraw = id => {
  ElMessageBox.confirm("该合同正在审批中,确定撤回吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      let params: ApiParams = {};
      params.id = id;
      withdrawProcureContract(params).then((response: ApiResponse) => {
        if (response.code === 200) {
          ElMessage.success("撤回成功");
        } else {
          ElMessage.error("提交失败");
          ElMessage.error("失败原因：" + response.msg);
        }
        getList();
      });
    })
    .catch(() => {
      ElMessage.error("已取消");
    });
};
// 初始化
onMounted(async () => {
  getAuditStatus();
  getList();
});
// 导航守卫
onUpdated(() => {
  getList();
});
</script>

<style lang="scss" scoped></style>
